package com.mark.markzxingcamera;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.mark.markzxingcamera.utils.DensityUtil;
import com.mark.markzxingcamera.utils.FileUtil;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_CODE = 10001;
    private static final int TAKE_PICTURE = 10003;
    private static final String FILE_PATH = "file_path";
    @BindView(R.id.btn_startQBR)
    ImageView btnStartQBR;
    @BindView(R.id.btn_openCamera)
    ImageView btnOpenCamera;
    //    @BindView(R.id.btn_save)
//    Button btnSave;
    @BindView(R.id.tv_result)
    EditText tvResult;


    private String fileName;
    private Uri imageUri;
    public static File tempFile;

    PermissionCheckUtil checkUtil;
    private Context context;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        ButterKnife.bind(this);
        checkUtil = new PermissionCheckUtil(this);

        initView();
    }

    /**
     * 初始化控件事件
     */
    private void initView() {
        btnStartQBR.setOnClickListener(this);
        btnOpenCamera.setOnClickListener(this);
//        btnSave.setOnClickListener(this);
//        btnSave.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_openCamera:
                Boolean isHasCamera = !checkUtil
                        .isNeedRequestPermissions(new String[]{Manifest.permission.CAMERA,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE});

                if (!isHasCamera) {
                    // 申请权限
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.CAMERA,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
                } else {
                    openCamera(this);
                }
                break;
            case R.id.btn_startQBR:
                Boolean isHasCamera2 = !checkUtil.isNeedRequestPermissions(new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE});

                if (!isHasCamera2) {
                    // 申请权限
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.CAMERA,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE}, 200);
                } else {
                    startQBR();
                }

                break;
        }

    }


    // 存储路径
    protected String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/mm/image";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    /**
     * 开始扫描
     */
    private void startQBR() {
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * 打开相机
     */
    private void openCamera(Activity activity) {
        //獲取系統版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (tvResult.getText().toString().length() > 0) {
            //执行拍照前，应该先判断SD卡是否存在
            fileName = tvResult.getText().toString();
            String SDState = Environment.getExternalStorageState();
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//"android.media.action.IMAGE_CAPTURE"
            if (SDState.equals(Environment.MEDIA_MOUNTED)) {

                File file = new File(FileUtil.getInstance().getImageFile(fileName));
                if (!file.exists()) {
                    file.mkdirs();
                    file.delete();
                    file.mkdirs();
                }
                // 从文件中创建uri
                imageUri = Uri.fromFile(file);
                if (currentapiVersion < 24) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    intent.putExtra(FILE_PATH, file.getAbsoluteFile());
                } else {
                    //兼容android7.0 使用共享文件的形式
                    ContentValues contentValues = new ContentValues(1);
                    contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
                    imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                }
                startActivityForResult(intent, TAKE_PICTURE);
                Log.d("tag", "filepath = " + file.getAbsoluteFile());

            } else {
                Toast.makeText(this, getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
            }

        } else {

            Toast.makeText(this, "请先进行扫描或输入条形码", Toast.LENGTH_SHORT).show();
        }

    }

    // 处理权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 100) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED
                    && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                //权限授予，拍照
                openCamera(this);
            } else {
                // 权限拒绝
                Toast.makeText(this, "由于缺少存储权限，打开相机失败", Toast.LENGTH_SHORT).show();

            }
        } else if (requestCode == 200) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED
                    && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                //权限授予，扫描
                startQBR();

            } else {
                // 权限拒绝
                Toast.makeText(this, "由于缺少存储权限，打开相机失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    //处理扫描结果（在界面上显示）
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            tvResult.setText(result);
                            Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                            Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                        }
                    }
                }
                break;
            case TAKE_PICTURE:
                if (resultCode == RESULT_OK) {
                    doPhoto(requestCode, data);
                }
                break;
        }

    }

    /**
     * 选择图片后，获取图片的路径
     *
     * @param requestCode
     * @param data
     */
    private void doPhoto(int requestCode, Intent data) {

        /**
         * 获取到的图片路径
         */
        String picPath = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
        // 获取当前时间
        Date date = new Date(System.currentTimeMillis());
        String waterMark = fileName;
        String dateStr = simpleDateFormat.format(date.getTime()).toString();

        if (requestCode == TAKE_PICTURE) {
            String[] pojo = {MediaStore.Images.Media.DATA};
            if (imageUri != null) {
                try {
                    Cursor cursor = getContentResolver().query(imageUri, pojo, null, null, null);
                    if (cursor != null) {
                        int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                        cursor.moveToFirst();
                        picPath = cursor.getString(columnIndex);
                        cursor.close();
                    } else {   //小米4上取不到图片路径
                        try {
                            String[] strPaths = imageUri.toString().split("//");
                            picPath = strPaths[1];
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (picPath != null && (picPath.toLowerCase().endsWith(".png") || picPath.toLowerCase().endsWith(".jpg"))) {
                        if (picPath == null || picPath.equals("")) {
                            Toast.makeText(this, "请重新拍照", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Toast.makeText(this, "pic = " + picPath, Toast.LENGTH_SHORT).show();
                        Bitmap bm = null;
                        try {
                            bm = FileUtil.getInstance().getImage(picPath, btnOpenCamera.getWidth(), btnOpenCamera.getHeight()); //获取限定宽高的bitmap，不限定则容易占用内存过大及OOM
                            if (bm == null) {
                                Toast.makeText(this, "请重新拍照", Toast.LENGTH_SHORT).show();
                            } else {
                                if (addWatermarkBitmap(bm, waterMark, dateStr, btnOpenCamera.getWidth(), btnOpenCamera.getHeight())) {
                                    Toast.makeText(this, "水印生成成功，文件已保存在 " + FileUtil.getInstance().IMAGE_PATH, Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            if (bm != null) {
                                bm.recycle();
                            }
                            System.gc();
                        }
                    } else {
                        Toast.makeText(this, "请重新拍照", Toast.LENGTH_LONG).show();
                    }
                } catch (NullPointerException e) {
                    Toast.makeText(this, "照片已存在，或请先删除在进行拍照", Toast.LENGTH_LONG).show();
                }
            }

        }
    }


    private boolean addWatermarkBitmap(Bitmap bitmap, String waterMark, String logo, int w, int h) {
        int destWidth = w;   //此处的bitmap已经限定好宽高
        int destHeight = h;
        Log.v("tag", "width = " + destWidth + " height = " + destHeight);

        Bitmap icon = Bitmap.createBitmap(destWidth, destHeight, Bitmap.Config.ARGB_8888); //定好宽高的全彩bitmap
        Canvas canvas = new Canvas(icon);//初始化画布绘制的图像到icon上

        Paint photoPaint = new Paint(); //建立画笔
        photoPaint.setDither(true); //获取跟清晰的图像采样
        photoPaint.setFilterBitmap(true);//过滤一些

        Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());//创建一个指定的新矩形的坐标
        Rect dst = new Rect(0, 0, destWidth, destHeight);//创建一个指定的新矩形的坐标
        canvas.drawBitmap(bitmap, src, dst, photoPaint);//将photo 缩放或则扩大到 dst使用的填充区photoPaint

        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//设置画笔
        //画笔粗细大小
        textPaint.setTextSize((float) DensityUtil.dp2px(context, 15));//字体大小
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);//采用默认的宽度
        textPaint.setAntiAlias(true);  //抗锯齿
        textPaint.setStrokeWidth(1);
        textPaint.setColor(Color.YELLOW);//采用的颜色
        //画布旋转-30度
        canvas.rotate(-30);
        textPaint.setAlpha(80);
        textPaint.setShadowLayer(1f, 0f, 3f, Color.LTGRAY);
        textPaint.setShadowLayer(3f, 1, 1, getResources().getColor(android.R.color.white));//影音的设置
        canvas.save();
        //行循环，从高度为0开始，向下每隔80dp开始绘制文字
        //获取要添加文字的宽度
        float textWidth = textPaint.measureText(waterMark);
        int index = 0;
        for (int positionY = -DensityUtil.dp2px(context, 30); positionY <= destHeight; positionY += DensityUtil.dp2px(context, 80)) {
            //设置每行文字开始绘制的位置,0.58是根据角度算出tan30°,后面的(index++ % 2) * textWidth是为了展示效果交错绘制
            float fromX = -0.58f * destHeight + (index++ % 2) * textWidth;
            //列循环，从每行的开始位置开始，向右每隔2倍宽度的距离开始绘制（文字间距1倍宽度）
            for (float positionX = fromX; positionX < destWidth; positionX += textWidth * 2) {
                //绘制文字
                canvas.drawText(waterMark, positionX, positionY, textPaint);
            }
        }
//        canvas.drawText(logo, destWidth / 2, destHeight - 45, textPaint);//绘制上去字，开始未知x,y采用那只笔绘制

//        textPaint.setStyle(Paint.Style.STROKE); //空心
//        canvas.drawText(waterMark, destWidth / 4, destHeight / 4, textPaint);
//        canvas.drawText(waterMark, destWidth / 2, destHeight / 2, textPaint);
//        canvas.drawText(waterMark, destWidth / 4 * 3, destHeight / 4 * 3, textPaint);
//        canvas.save(Canvas.ALL_SAVE_FLAG);

        canvas.restore();
        bitmap.recycle();
        btnOpenCamera.setImageBitmap(icon);
        return FileUtil.getInstance().saveMyBitmap(icon, tvResult.getText().toString()); //保存至文件
//        return true;
    }

}
